<?php
/**
 * 2016/10/22 09:59:31 
 * 张树超
 * 用户中心
 * http://yshop.huiyouzan.com/
 */
namespace Home\Controller;

use Think\Controller;

class CenterController extends HomeController
{
	public function __construct() {
		parent::__construct();
        //判断是否登录
        hook('login','','true');
	}
	
	/**
	 * 首页
	 */
    public function index() {
		$this->display();
    }

	/**
	 * 个人资料
	 */
	public function info() {
		if(IS_POST) {
			$act = I('post.act','','strip_tags');
			if($act == 'act_edit_profile') { // 修改个人信息
				$User = D('Home/user');
				if (!$User->create()){
					$this->alert($User->getError()); // 验证提示
				} else {
					$msg = $User->profile();
					if(empty($msg)) {
						$this->alert('修改失败！');
					} else {
						$_SESSION['member']['mobile'] = I('post.mobile',$_SESSION['member']['mobile'],'intval');
						$_SESSION['member']['email'] = I('post.email',$_SESSION['member']['email'],'strip_tags');
						$this->alert('修改成功！',U('Center/info'));
					}
				}
				die();
			}

			if($act == 'act_edit_password') { // 修改密码
				$User = D('Home/user');
				if (!$User->create($_POST,1)){
					$this->alert($User->getError()); // 验证提示
				} else {
					$old_password = I('post.old_password','','trim,strip_tags,md5');
					if($old_password == strip_tags($_SESSION['member']['password'])) {
						$msg = $User->password();
						if(empty($msg)) {
							$this->alert('修改失败！');
						} else {
							$_SESSION['member']['password'] = I('post.password','','trim,strip_tags,md5');
							$this->alert('修改成功！',U('Center/info'));
						}
					} else {
						$this->alert('修改失败，原密码错误！');
					}
				}
				die();
			}
		}

		//获取个人信息
        $User = D("User");
        $info = $User->find(session("member.id"));
//        dump($info);
        $this->assign("info",$info);
		$this->display();
	}

	public function bindwechat(){
		$wechat = session("wechat");
		$member = session("member");
		if(!$wechat["openid"]){
			$this->alert("无法获取Openid");
		}
		if(!$member["id"]){
			$this->alert("请先登录");
		}

		// 更新用户Openid
		$User = D("User");
		$data = array(
			'openid'=>$wechat['openid'],
		);
		$res = $User->where("id={$member['id']}")->setField("openid",$wechat["openid"]);
		$member["openid"] = $wechat["openid"];
		session("member",$member);
		$this->alert("绑定成功",U("Center/index"),1);

	}

	public function delewechat(){
		$member = session("member");
		if(!$member["id"]){
			$this->alert("请先登录");
		}

		// 删除用户Openid
		$User = D("User");
		$data = array(
			'openid'=>"",
		);
		$User->where("id={$member["id"]}")->setField("openid","");
		$member["openid"] = "";
		session("member",$member);
		$this->alert("解绑成功",U("Center/index"),1);

	}
    /**
     * 个人资料ajax修改
     */
    public function ajax_info(){
		//必须登录
		$uid = session("member.id");
		if(!($uid>0)){
			$this->ajaxReturn(array('code'=>0,'msg'=>'未登录'));
		}

        $data = array();
        switch($_POST['name']){
            case 'portrait';
                $data['portrait'] = I("post.value",'');
                break;
            case 'username':
                $data['username'] = I("post.value",'');
                break;
            case 'sex':
                $data['sex'] = I("post.value",'');
                break;
            case 'company':
                $data['company'] = I("post.value",'');
                break;
			case 'address':
				$data['address'] = I("post.value",'');
				break;
			case 'email':
				$data['email'] = I("post.value",'');
				break;
			case 'password':
				if(I("post.value",'')){
					$data['password']=md5(I("post.value",''));
				}
				break;
			default:
				$this->ajaxReturn(array('code'=>0,'msg'=>'修改字段非法'));
        }

        $User = M("User");
        if($User->where("id={$uid}")->save($data)){
			if('password' == $_POST['name']){
				session("member.password",$data['password']);
			}
			$this->ajaxReturn(array('code'=>1));
		}else{
			$this->ajaxReturn(array('code'=>0,'msg'=>$User->getError()));
		}
    }
	/**
	 * 个人资料编辑 头像
	 */
	public function portrait(){
		//必须登录
		$uid = session("member.id");
		if(!($uid>0)){
			hook("login",'',true);
		}
		if(!IS_POST){
			$this->alert('未选择图片失败！');
		}
		/* 调用文件上传组件上传文件 */
		$Picture    =   D('Picture');
		$pic_driver = C('PICTURE_UPLOAD_DRIVER');
		$info = $Picture->upload(
			$_FILES,
			C('PICTURE_UPLOAD'),
			C('PICTURE_UPLOAD_DRIVER'),
			C("UPLOAD_{$pic_driver}_CONFIG")
		);
		/* 记录图片信息 */
		$User = M("User");
//		dump($info);
		if($info && $info['img']['id']>0 && $User->where("id={$uid}")->save(array('portrait'=>$info['img']['id']))){
			$this->alert('图片上传成功！');
		} else {
			$this->alert('图片上传失败！'.$Picture->getError());
		}


	}



	/**
	 * 我的订单
	 */
	public function order() {
		$Order = D("Order");
		$orders = $Order->getOrder(session('member.id'));
		trace($orders,'orders');
		$this->assign('orders',$orders);
		$this->display();
	}

	/**
	 * 我的收藏
	 */
	public function collection() {
		$user_id = session('member.id');
		$Collection = D("Collection");
		$collections = $Collection->getCollection($user_id);
		$Goods = D("Goods");

		if(!empty($collections)){
			foreach ($collections as $k=>&$v){
//				$collection['goods'] = $Goods->getDetail($user_id);
				if( 'fade' != I('fade','') && !empty($goods = $Goods->getDetail($v['goods_id']))) {
					trace($goods, 'goods');
					$v['goods_title'] = $goods['title'];
					$v['goods_price'] = $goods['price'];
					$v['goods_multimage'] = $goods['multimage'];
					$v['goods_pubend'] = $goods['pubend'];
				}elseif('fade' == I('fade','') && !empty($goods = $Goods->getDetail($v['goods_id']))){
					trace('fade','fade');
					unset($collections[$k]);
				}else{
					$v['goods_price'] = 0;
					$v['goods_id'] = 0;
				}
			}unset($v);
		}
		$this->assign('collections',$collections);
		$this->display();
	}
	public function collection_add(){
		$goods_id = I("goods_id",0);
		if($goods_id){
			if($info = D("Goods")->find($goods_id)){
				$data = array(
					'user_id'=>session("member.id"),
					'goods_id'=>$goods_id,
					'goods_title'=>$info['title'],
					'goods_price'=>$info['price'],
					'goods_multimage'=>$info['multimage']
				);
				$Collection = D("Collection");
				if($res = $Collection->where("`goods_id`={$goods_id}")->select()){
					if($data = $Collection->create($data) && $Collection->where("`goods_id`={$goods_id}")->save($data)){
						$this->alert('增加成功！',$_SERVER['HTTP_REFERER']);
					}else{
						$this->alert($Collection->getError());
					}
				} else {
					if ($data = $Collection->create($data) && $Collection->add($data)) {
						$this->alert('增加成功！', $_SERVER['HTTP_REFERER']);
					} else {
						$this->alert($Collection->getError());
					}
				}

			}
		}
	}
	public function collection_ajax_add($id){
		$goods_id = I("id",0);
		if($goods_id){
			if($info = D("Goods")->find($goods_id)){
				$data = array(
					'user_id'=>session("member.id"),
					'goods_id'=>$goods_id,
					'goods_title'=>$info['title'],
					'goods_price'=>$info['price'],
					'goods_multimage'=>$info['multimage']
				);
				$Collection = D("Collection");

				if($Collection->update($data)){
					$this->ajaxReturn(array('code'=>1,'msg'=>'添加收藏成功'));
				}else{
					$this->ajaxReturn(array('code'=>0,'msg'=>$Collection->getError()));
				}
//				if($res = $Collection->where("`goods_id`={$goods_id}")->select()){
//					if($data = $Collection->create($data) && $Collection->where("`goods_id`={$goods_id}")->save($data)){
////						$this->alert('增加成功！',$_SERVER['HTTP_REFERER']);
//						$this->ajaxReturn(array('code'=>1,'msg'=>'添加收藏成功'));
//					}else{
////						$this->alert($Collection->getError());
//						$this->ajaxReturn(array('code'=>0,'msg'=>$Collection->getError()));
//					}
//				} else {
//					if ($data = $Collection->create($data) && $Collection->add($data)) {
////						$this->alert('增加成功！', $_SERVER['HTTP_REFERER']);
//						$this->ajaxReturn(array('code'=>1,'msg'=>'添加收藏成功'));
//					} else {
////						$this->alert($Collection->getError());
//						$this->ajaxReturn(array('code'=>0,'msg'=>$Collection->getError()));
//					}
//				}

			}
		}
	}
	public function collection_edit(){

		if(IS_POST){
			dump($_POST);
			
			
		}else{
			$user_id = session('member.id');
			$Collection = D("Collection");
			$collections = $Collection->getCollection($user_id);
			$Goods = D("Goods");

			if(!empty($collections)){
				foreach ($collections as $k=>&$v){
//				$collection['goods'] = $Goods->getDetail($user_id);
					if( 'fade' != I('fade','') && !empty($goods = $Goods->getDetail($v['goods_id']))) {
						trace($goods, 'goods');
						$v['goods_title'] = $goods['title'];
						$v['goods_price'] = $goods['price'];
						$v['goods_multimage'] = $goods['multimage'];
					}else{
						$v['goods_price'] = 0;
					}
				}
			}
			trace($collections,'collections');
			$this->assign('collections',$collections);

			$this->display();
		}

	}

	function collection_delete(){
		$id = I('collection_id','');
		$map['id'] = is_array($id)?array('in',$id):$id;
		$Collection = M("Collection");
		$msg = $Collection->where($map)->delete();
		if(!empty($msg)) {
			$this->alert('删除成功！',U('Center/collection'),0);
		} else {
			$this->alert('删除失败！');
		}
	}

	/**
	 * 在线客服
	 */
	public function online(){
		$this->display();
	}
	/**
	 * 收货人信息
	 */
	public function address() {
		$where['user_id'] = intval($_SESSION['member']['id']);
		$list = D('address')->where($where)->order('id desc')->select();
		$this->assign('list',$list);
		$this->display();
	}

	/**
	 * 修改收货人信息
	 */
	public function address_modify() {
		if(IS_POST) {
			$id = I('post.address_id','','intval');
			$data['name'] = I('post.name','','strip_tags,trim');
			if(empty($data['name'])) {
				$this->alert('收货人不能为空！');
			}
			$data['mobile'] = I('post.mobile','','intval');
			if(!preg_match("/^1[3|4|5|6|7|8]\d{9}/",$data['mobile'])) {
				$this->alert('联系电话格式错误！');
			}
			$data['email'] = I('post.email','','strip_tags,trim');
			if(!preg_match("/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i",$data['email'])) {
				$this->alert('邮箱格式错误！');
			}
			$data['address'] = I('post.address','','strip_tags,trim');
			if(empty($data)) {
				$this->alert('详细地址不能为空！');
			}
			$address = D('address');
			if(!empty($id)) { // 判断提交是修改还是添加
				$msg = $address->where(array('id'=>$id))->save($data);
			} else {
				$data['user_id'] = intval($_SESSION['member']['id']);
				$msg = $address->add($data);
			}
			if(empty($msg)) {
				$this->alert('操作失败！');
			} else {
				$this->alert('操作成功！',U('Center/address'));
			}
		}

		$id = I('get.id','','intval');
		if(!empty($id)) { // 判断是修改还是添加
			$info = D('address')->find($id); // 获取地址信息
			$this->assign('info',$info);
		}
		$this->display();
	}

	/**
	 * 删除收货地址
	 */
	public function address_del() {
		$id = I('get.id','','intval');
		$msg = D('address')->delete($id);
		if(!empty($msg)) {
			$this->alert('删除成功！',U('Center/address'));
		} else {
			$this->alert('删除失败！');
		}
	}

	/**
	 * 成功跳转
	 */
	public function alert($msg,$url,$time=-1) {
		$this->assign('info',array('msg'=>$msg,'url'=>$url));
		$this->assign("time",$time);
		$this->display('Notice/location');
		die();
	}

}
